import { ref, getCurrentInstance } from "vue";
import {
	getDeviceShadowApi,
	getDeviceProcessApi,
	setDefaultPlansApi,
	getDeviceTipsApi,
	plansCtrlApi,
} from "@/service/index";
import { useDeviceStore } from "@/stores/device";
import { useI18n } from "vue-i18n";
import parseMsg from "@/utils/getMessage";
import { useDevice } from "@/utils/device";

// 类型定义
interface DeviceShadowParams {
	device_sn: string;
	plan_id?: string;
}

interface GarbageStatus {
	timestamp: number;
}

interface TimeTimingItem {
	plan_id?: string;
	timestamp?: number;
	plan_status?: string;
}
interface Task {
	zone_id?: string;
	path_id?: string;
	task_type: number;
	path_percentage: number;
}
interface DeviceProcessResponse {
	code: number;
	data: {
		tasks: Task[];
	};
}
interface CountDownPopup {
	countDownCon: string;
	timeInfoBefore: string;
	timeInfoAfter: string;
}
interface PlanCtrlParams {
	device_sn: string;
	plan_id: string;
	cmd: number;
	map_id: string;
}
export const useDeviceInfo = () => {
	// 响应式数据
	const deviceStatus = ref<DeviceStatus | null>(null);
	const loadingState = ref<boolean>(false);
	const countDownTime = ref<number>(20);
	const getDeviceShadowTimeOut = ref<number | null>(null);
	const getDeviceTipTimeOut = ref<number | null>(null);
	const deviceStore = useDeviceStore();
	const deviceSn = ref("");
	const isLoading = ref(false);
	const timeOutProcess = ref<number | null>(null);
	const timeTimingType = ref<number>(0);
	const timerSetInterval = ref<number | null>(null);
	const isTimeTimingOk = ref<boolean>(false);
	const timeTimingObj = ref<TimeTimingItem | null>(null);
	const instance: any = getCurrentInstance();
	const { getPlanList } = useDevice();
	const countDownPopup = ref<CountDownPopup>({
		countDownCon: "",
		timeInfoBefore: "",
		timeInfoAfter: "",
	});
	const { t } = useI18n();
	// 获取设备进程
	const getDeviceProcess = async (num?: number): Promise<void> => {
		try {
			const { data } = await getDeviceProcessApi({
				device_sn: deviceSn.value,
			});
			if (data && !data.code) {
				deviceStore.deviceProgress = data.data;
				if (data.tasks && data.tasks.length && !num) {
					processeData(data.data);
				}
			}
		} catch (error) {
			console.error("获取设备进程失败:", error);
		} finally {
		}
	};

	// 处理进程数据
	const processeData = (
		responseData: DeviceProcessResponse["data"]
	): void => {
		console.log("获取进程数据");
		console.log(responseData);
		const tasks = responseData.tasks;
		// 整合多圈数据
		const consolidatedTasks = consolidateTasks(tasks);

		// 根据模式处理数据
		let processedData: ZoneItem[] = [];

		if (deviceStore?.defaultPlan?.pattern === 3) {
			processedData = processPattern3(consolidatedTasks);
		}
		// 设置zIndex
		deviceStore.zones = setZIndex(processedData, tasks) || [];
		// 设置下一次请求
		timeOutProcess.value = setTimeout(getDeviceProcess, 5000);
	};

	// 整合任务数据
	const consolidateTasks = (tasks: Task[]): Task[] => {
		const consolidated: Task[] = [];
		tasks.forEach((task) => {
			const existingIndex = consolidated.findIndex(
				(existingTask) =>
					(existingTask.zone_id &&
						task.zone_id &&
						existingTask.zone_id === task.zone_id) ||
					(existingTask.path_id &&
						task.path_id &&
						existingTask.path_id === task.path_id)
			);

			if (existingIndex === -1) {
				// 新任务，直接添加
				consolidated.push({ ...task });
			} else {
				// 已存在相同zone_id或path_id的任务，检查task_type
				if (consolidated[existingIndex].task_type === task.task_type) {
					// 相同task_type，更新为最新数据
					consolidated[existingIndex] = { ...task };
				} else {
					// 不同task_type，也更新为最新数据
					consolidated[existingIndex] = { ...task };
				}
			}
		});
		return consolidated;
	};

	// 处理模式3的数据
	const processPattern3 = (tasks: Task[]): ZoneItem[] => {
		const result: ZoneItem[] = [];
		deviceStore.zonesList.forEach((zone, index) => {
			const task = tasks[index];
			if (task) {
				result.push({
					progress: Math.min(task.path_percentage, 1),
					path_id: task.path_id,
					task_type: task.task_type,
					zone_id: task.zone_id,
					path: zone.path,
					type: zone.type,
					url: zone.url,
					x: zone.x,
					y: zone.y,
					zIndex: 1,
				});
			} else {
				result.push({
					progress: 0,
					path_id: zone.path_id,
					task_type: zone.task_type,
					zone_id: zone.zone_id,
					path: zone.path,
					type: zone.type,
					url: zone.url,
					x: zone.x,
					y: zone.y,
					zIndex: 1,
				});
			}
		});
		return result;
	};

	// 设置zIndex
	const setZIndex = (processedData: ZoneItem[], originalTasks: Task[]) => {
		if (originalTasks.length === 0) return;
		const lastTask = originalTasks[originalTasks.length - 1];
		processedData.forEach((item) => {
			if (
				(item.zone_id &&
					lastTask.zone_id &&
					item.zone_id === lastTask.zone_id &&
					item.task_type === lastTask.task_type) ||
				(item.path_id &&
					lastTask.path_id &&
					item.path_id === lastTask.path_id &&
					item.task_type === lastTask.task_type)
			) {
				item.zIndex = 2;
			}
		});
		return processedData;
	};
	const once = ref(false);
	// 获取设备信息的方法
	const getDeviceShadow = async (device_sn?: string): Promise<void> => {
		try {
			if (!isLoading.value) {
				deviceSn.value = device_sn || "";
			} // 避免重复赋值
			isLoading.value = true;
			const params: DeviceShadowParams = {
				device_sn: deviceSn.value,
			};
			// if (deviceStore?.defaultPlan?.planid) {
			// 	params.plan_id = deviceStore.defaultPlan?.planid;
			// }
			const { data } = await getDeviceShadowApi(params);
			if (data && !data.code) {
				processDeviceData(data.data);
			}
		} catch (error) {
			console.error("获取设备信息失败:", error);
		} finally {
			// 设置下一次请求
			getDeviceShadowTimeOut.value = setTimeout(getDeviceShadow, 2000);
		}
	};

	const CHARGING_STATUS = 4; // 充电状态
	// 检查是否需要切换计划
	const shouldSwitchPlan = (tipData: DeviceTipsResponse["data"]): boolean => {
		if (!tipData) return false;

		const { defaultPlan, deviceStatus } = deviceStore;

		// 基础条件检查
		const isSameMap = defaultPlan?.map_id === tipData.map_id;
		const isNotCharging = deviceStatus?.status !== CHARGING_STATUS;
		const hasValidPlanIds = defaultPlan?.planid && tipData.plan_id;
		const isDifferentPlan = tipData.plan_id !== defaultPlan?.planid;

		return isSameMap && isNotCharging && hasValidPlanIds && isDifferentPlan;
	};
	// 获取设备提示
	const getDeviceTips = async (device_sn?: string): Promise<void> => {
		try {
			if (!deviceSn.value) {
				deviceSn.value = device_sn || "";
			}
			const { data } = await getDeviceTipsApi({
				device_sn: deviceSn.value,
			});
			if (data.code === 0) {
				if (!data.data) return;
				if (deviceStore.tipsMsg !== data.data.msg) {
					deviceStore.tipsMsg = data.data.msg;
				}
				if (data.data.msg) {
					getDeviceProcess(1);
				}
				// 检查是否需要切换计划
				if (shouldSwitchPlan(data.data)) {
					await setDefaultPlans(data.data);
				}
			} else {
				instance.proxy.$message(data.msg, "error");
			}
		} catch (error) {
			console.error("获取设备提示失败:", error);
			instance.proxy.$message(error, "error");
		} finally {
			getDeviceTipTimeOut.value = setTimeout(getDeviceTips, 5000);
		}
	};
	// 处理设备数据
	const processDeviceData = (data: DeviceStatus): void => {
		deviceStatus.value = data;
		deviceStore.deviceStatus = data;
		deviceStore.setDeviceStatus(data);
		// 处理橡胶状态
		if (data.rubber === "auto") {
			data.rubber = "huge";
		}
		// 设置显示灰色状态
		deviceStore.showGray = data.status !== 1;
		if (data.status !== 1 && !once.value) {
			getDeviceProcess();
		}
		once.value = true;
		// 设置加载状态
		loadingState.value = data.status === 8;

		// 保存设备位置
		deviceStore.devicePosition = data.position.pos;
		// 处理定时状态
		if (data.timing_status) {
			processTimingStatus(data.timing_status);
		}

		// 处理电池状态
		if (data.battery_status) {
			processBatteryStatus(data.battery_status);
		}
		// 处理垃圾状态
		if (
			data.garbage_inventory >= data.garbage_value &&
			data.garbage_status
		) {
			processGarbageStatus(data.garbage_status, data.garbage_mode);
		}

		// 清理过期的定时记录
		cleanupTimeTiming();
	};

	// 处理定时状态
	const processTimingStatus = (timingStatus: TimeTimingItem): void => {
		const currentTime = Date.now();
		const timeDiff = currentTime - timingStatus.timestamp;

		if (timeDiff > 0 && timeDiff < 60000 * 20) {
			handleTimeTiming(timingStatus, 1);
		} else {
			countDownTime.value = 20;
		}
	};

	// 处理电池状态
	const processBatteryStatus = (batteryStatus: TimeTimingItem): void => {
		const currentTime = Date.now();
		const timeDiff = currentTime - batteryStatus.timestamp;

		if (timeDiff > 0 && timeDiff < 60000 * 20) {
			handleTimeTiming(batteryStatus, 2);
		} else {
			countDownTime.value = 20;
		}
	};

	// 处理垃圾状态
	const processGarbageStatus = (
		garbageStatus: GarbageStatus,
		garbageMode?: string
	): void => {
		const currentTime = Date.now();
		const timeDiff = currentTime - garbageStatus.timestamp;
		const overflowTime = deviceStatus.value?.overflow_time || 20;

		if (timeDiff > 0 && timeDiff < 60000 * overflowTime) {
			handleTimeTiming(garbageStatus, 3, garbageMode);
		}
	};

	// 处理时间定时逻辑
	const handleTimeTiming = (
		item: TimeTimingItem,
		type: number,
		garbageMode?: string
	): void => {
		const currentTime = Date.now();
		let timeTiming: TimeTimingItem[] =
			uni.getStorageSync("timeTiming") || [];

		// 检查是否已经处理过
		const isAlreadyProcessed = timeTiming.some(
			(timingItem) =>
				timingItem.timestamp === item.timestamp &&
				(!item.plan_id || timingItem.plan_id === item.plan_id)
		);

		if (!isAlreadyProcessed) {
			// 保存当前时间
			uni.setStorageSync("timeNow", currentTime.toString());

			// 添加新记录
			timeTiming.push(item);
			uni.setStorageSync("timeTiming", timeTiming);

			// 打开定时
			timeTimingOpen(type, item, garbageMode);
		}
	};

	// 清理过期的定时记录
	const cleanupTimeTiming = (): void => {
		let timeTiming: TimeTimingItem[] =
			uni.getStorageSync("timeTiming") || [];
		const currentTime = Date.now();
		const oneDayInMs = 60000 * 60 * 24;

		// 过滤掉24小时前的记录
		const filteredTiming = timeTiming.filter(
			(item) => currentTime - item.timestamp <= oneDayInMs
		);

		if (filteredTiming.length !== timeTiming.length) {
			uni.setStorageSync("timeTiming", filteredTiming);
		}
	};

	// 定时打开方法
	const timeTimingOpen = (
		type: number,
		item: TimeTimingItem,
		mode: string = ""
	): void => {
		timeTimingType.value = type;
		const timeNow = uni.getStorageSync("timeNow");
		const currentTime = Date.now();
		const timeDiff = currentTime - timeNow;

		// 根据类型处理不同的弹窗逻辑
		switch (type) {
			case 1:
				handleType1(item);
				break;
			case 2:
				handleType2();
				break;
			case 3:
				handleType3(mode);
				return; // 类型3直接返回，不执行后续倒计时逻辑
			default:
				console.warn("未知的定时任务类型:", type);
				return;
		}

		// 处理倒计时逻辑
		handleCountDown(timeDiff, type);
	};
	// 处理类型1的逻辑
	const handleType1 = (item: TimeTimingItem): void => {
		if (item.plan_status === "working") {
			countDownPopup.value = {
				countDownCon: t("notice.timeTask1"),
				timeInfoBefore: t("notice.timeInfoBefore1"),
				timeInfoAfter: t("notice.timeInfoAfter1"),
			};
			timeTimingObj.value = item;
			isTimeTimingOk.value = true;
		}
		// 如果plan_status不是'working'，直接返回不执行任何操作
	};

	// 处理类型2的逻辑
	const handleType2 = (): void => {
		countDownPopup.value = {
			countDownCon: t("notice.timeTask2"),
			timeInfoBefore: t("notice.timeInfoBefore2"),
			timeInfoAfter: t("notice.timeInfoAfter2"),
		};
		isTimeTimingOk.value = true;
	};

	// 处理类型3的逻辑
	const handleType3 = (mode: string): void => {
		let contentMsg = "";

		switch (mode) {
			case "recall":
				contentMsg = t("hint.rubbish1");
				break;
			case "pause":
				contentMsg = t("hint.rubbish2");
				break;
			case "continue":
				contentMsg = t("hint.rubbish3");
				break;
			default:
				contentMsg = t("hint.rubbish1"); // 默认值
		}
		// 弹窗部分后续处理
		// if (!isShowModal.value) {
		// 	isShowModal.value = true;

		// 	uni.showModal({
		// 		title: t("hint"),
		// 		content: contentMsg,
		// 		showCancel: false,
		// 		success: () => {
		// 			isShowModal.value = false;
		// 		},
		// 	});
		// }
	};
	// 处理倒计时逻辑
	const handleCountDown = (timeDiff: number, type: number): void => {
		if (timeDiff >= 0 && timeDiff < 20000) {
			if (countDownTime.value === 20) {
				// 打开倒计时弹窗（假设有对应的组件引用）
				// this.$refs.countDownPopup.open();

				// 开启倒计时
				startCountDown(type);
			} else {
				// 关闭倒计时弹窗
				// this.$refs.countDownPopup.close();
			}
		}
	};
	// 清洁计划控制 1:开始 2:终止 3:暂停 4:恢复, 5:召回, 6:召回取消, 7:继续清扫
	const plansCtrl = async (
		cmd: number,
		tips: string,
		waitbegin: boolean = false
	): Promise<void> => {
		try {
			const params: PlanCtrlParams = {
				device_sn: deviceSn.value,
				plan_id: deviceStore?.defaultPlan?.planid,
				cmd: cmd,
				map_id: deviceStore?.defaultPlan?.map_id,
			};

			const { data } = await plansCtrlApi(params);

			if (!data.code) {
				// 成功处理
				handleSuccess(cmd, tips, waitbegin);
			} else {
				// 错误处理
				const errorMessage = parseMsg(data.msg || t("errors.unknown"));
				instance.proxy.$message(errorMessage, "error");
			}
		} catch (error) {
			console.error("计划控制请求失败:", error);
			instance.proxy.$message(t("tips.requestFailed"), "error");
		}
	};
	// 成功处理
	const handleSuccess = (
		cmd: number,
		tips: string,
		waitbegin: boolean
	): void => {
		// 显示成功消息
		instance.proxy.$message(t(`tips.${tips}`), "success", 3000);

		// 特殊处理终止命令
		if (cmd === 2) {
			handleTerminationCommand(waitbegin);
		}
	};

	// 处理终止命令
	const handleTerminationCommand = (waitbegin: boolean): void => {
		if (isTimeTimingOk.value) {
			isTimeTimingOk.value = false;
			setPlanIdRun();
		}

		if (waitbegin) {
			plansCtrl(1, "startPlan");
		}
	};
	// 设置默认计划
	const setDefaultPlans = async (device: Device): Promise<boolean> => {
		try {
			const params: SetDefaultPlansParams = {
				device_sn: deviceSn.value,
				planid: device.planid,
			};
			const response = await setDefaultPlansApi(params);
			if (response.data.code === 0) {
				// 成功时获取计划列表
				getPlanList();
				instance.proxy.$message("默认计划设置成功", "success");
				return true;
			}
		} catch (error) {
			instance.proxy.$message(error, "error");
			return false;
		} finally {
		}
	};

	// 设置默认清洁任务并执行
	const setPlanIdRun = (): void => {
		if (!timeTimingObj.value) return;

		const planId = timeTimingObj.value.plan_id;
		const targetPlan = deviceStore.planList.find(
			(item) => item.planid === planId
		);

		if (targetPlan) {
			deviceStore.defaultPlan = targetPlan;
			setDefaultPlans(targetPlan);
			plansCtrl(1, "startPlan");
		}
	};
	// 开始倒计时
	const startCountDown = (type: number): void => {
		if (timerSetInterval.value) {
			clearInterval(timerSetInterval.value);
		}

		timerSetInterval.value = setInterval(() => {
			countDownTime.value -= 1;

			if (countDownTime.value === 0) {
				stopCountDown();

				// 类型2的特殊处理
				if (type === 2) {
					plansCtrl(4, "continuePlan");
				}
			}
		}, 1000);
	};

	// 停止倒计时
	const stopCountDown = (): void => {
		// 关闭倒计时弹窗
		// this.$refs.countDownPopup.close();

		countDownTime.value = 20;

		if (timerSetInterval.value) {
			clearInterval(timerSetInterval.value);
			timerSetInterval.value = null;
		}
	};

	const clearTime = (num?: number) => {
		if (getDeviceTipTimeOut.value) {
			clearTimeout(getDeviceTipTimeOut.value);
			getDeviceTipTimeOut.value = null;
		}
		if (!num) {
			if (getDeviceShadowTimeOut.value) {
				clearTimeout(getDeviceShadowTimeOut.value);
				getDeviceShadowTimeOut.value = null;
			}
			if (timeOutProcess.value) {
				clearTimeout(timeOutProcess.value);
				timeOutProcess.value = null;
			}
			if (timerSetInterval.value) {
				clearTimeout(timerSetInterval.value);
				timerSetInterval.value = null;
			}
		}
	};

	// 导出需要在模板中使用的内容
	return {
		deviceStatus,
		loadingState,
		countDownTime,
		getDeviceShadow,
		clearTime,
		getDeviceTips,
	};
};
export default {
	useDeviceInfo,
};
